package top.codedance.iotp.registy.net.handle;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.enums.HttpStatus;
import top.codedance.iotp.registy.RegistryApplication;
import org.apache.log4j.Logger;

import java.nio.charset.StandardCharsets;

public abstract class AdapterController implements Controller {
    private Logger logger = RegistryApplication.getLogger(AdapterController.class);
    private JSONObject jsonObject = new JSONObject();

    public String doHandler(byte[] bodyArr) {
        try {
            String bodyString = new String(bodyArr, StandardCharsets.UTF_8);
            this.jsonObject = JSONObject.parseObject(bodyString);
            return doSubHandler(this.jsonObject);
        } catch (Exception e) {
            logger.debug(e.getMessage());
            return response500("Programe exception");
        }
    }

    /**
     * 处理的controller需要实现
     * @param body
     * @return
     */
    public abstract String doSubHandler(JSONObject body);

    protected String response(int statusCode, Object msg, Object data) {
        JSONObject result = new JSONObject();
        result.put("status", statusCode);
        if(HttpStatus.OK.getCode() != statusCode) {
            result.put("message", msg);
        }else{
            result.put("data", data);
        }
        return result.toJSONString();
    }

    protected String okResponse(Object data) {
        return response(HttpStatus.OK.getCode(), "", data);
    }

    protected String errResponse(int statusCode, Object msg) {
        return response(statusCode, msg, null);
    }

    protected String response500(String msg) {
        return errResponse(HttpStatus.INTERNAL_SERVER_ERROR.getCode(), msg);
    }

    protected String response403(String msg){
        return errResponse(HttpStatus.FORBIDDEN.getCode(), msg);
    }
}